import requests
import time

# ls -1 *.txt | sort -nr | sed 's/\.txt$//' | sed 's/.*/"&"/'

# haihui github person token
# token = "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"

# wanghh2000 token
token = "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"

def read_issue_comments(f, issue_number, page: int = 1):
    url = f"https://api.github.com/repos/OpenCSGs/csghub/issues/{issue_number}/comments"
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    params = {
        "per_page": 100,     # Number of issues per page
        "page": page        # Page number to fetch issues from
    }
    response = requests.get(url, headers=headers, params=params)
    if response.status_code == 200:
        issue_comments = response.json()
        for comment in issue_comments:
            comment_body = comment['body']
            f.write(f"{comment_body}\n")
            # print(comment_body)
    else:
        print(f"Failed to retrieve issue comments {url} :", response.status_code)

def read_issue_all_comments(f, issue_number):
    for page in range(1, 5):
       read_issue_comments(f, issue_number, page)
       time.sleep(10)

def read_one_issue(issue_number):
    # Replace 'owner' and 'repo' with the actual owner and repository name
    url = f"https://api.github.com/repos/OpenCSGs/csghub/issues/{issue_number}"
    # print(url)
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28",
    }

    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        issue = response.json()
        if "pull_request" not in issue:
            issue_number = issue['number']
            print(f"######################### {issue_number} ###############################")

            issue_title = issue['title']
            issue_body = issue['body']
            
            with open(f"issues/{issue_number}.txt", 'a', encoding='utf-8') as f:
                # print(f"Issue #{issue_number} :{issue_title}")
                f.write(f"{issue_title}\n")
                f.write(f"{issue_body}\n")
                read_issue_all_comments(f, issue_number)
    else:
        print(f"Failed to retrieve issues {url} :", response.status_code)

def read_repo_issues(page: int):
    # Replace 'owner' and 'repo' with the actual owner and repository name
    url = "https://api.github.com/repos/OpenCSGs/csghub/issues"
    
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "X-GitHub-Api-Version": "2022-11-28",
    }

    params = {
        # "state": "closed",  # Can be one of: open, closed, all 
        # "state": "open",  # Can be one of: open, closed, all
        "state": "all",  # Can be one of: open, closed, all
        "sort": "created",  # Sort by creation date
        # "direction": "asc", # Ascending order (oldest first)
        "direction": "desc", # Ascending order (oldest first)
        "per_page": 60,     # Number of issues per page
        "page": page        # Page number to fetch issues from
    }

    response = requests.get(url, headers=headers, params=params)

    if response.status_code == 200:
        issues = response.json()
        for issue in issues:
            if "pull_request" not in issue:
                issue_number = issue['number']
                print(f"######################### {issue_number} ###############################")
                if int(issue_number) < 1422:
                    return
                issue_title = issue['title']
                issue_body = issue['body']
                
                with open(f"issues/{issue_number}.txt", 'a', encoding='utf-8') as f:
                    # print(f"Issue #{issue_number} :{issue_title}")
                    f.write(f"{issue_title}\n")
                    f.write(f"{issue_body}\n")
                    read_issue_all_comments(f, issue_number)
    else:
        print(f"Failed to retrieve issues {url} :", response.status_code)

def read_all_issues():
    page_count = 30
    # page_count = 2
    for page in range(1, page_count):
       read_repo_issues(page)
       time.sleep(10)

def read_list_issues():
    issue_numbers = ["1429"]
    for issue_number in issue_numbers:
        read_one_issue(issue_number)

if __name__ == "__main__":
    # read_all_issues()
    read_list_issues()
